package com.hyjoy.web.servlet;

import com.hyjoy.constant.Constant;
import com.hyjoy.entity.*;
import com.hyjoy.service.OrderService;
import com.hyjoy.service.impl.OrderServiceImpl;
import com.hyjoy.util.BeanFactory;
import com.hyjoy.util.PaymentUtil;
import com.hyjoy.util.UUIDUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.ResourceBundle;

/**
 * Created by hyjoy on 2018/4/5.
 */
public class OrderServlet extends BaseServlet {

    /**
     * 保存订单
     *
     * @param request
     * @param response
     * @return
     */
    public String save(HttpServletRequest request, HttpServletResponse response) {
        try {
// 从session中获取user
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                // 未登陆 提示
                request.setAttribute("msg", "请先登录！");
                return "/jsp/msg.jsp";
            }
            // 获取购物车
            Cart cart = (Cart) request.getSession().getAttribute("cart");
            // 封装订单对象
            Order order = new Order();
            order.setOid(UUIDUtils.getUUID());
            order.setOrdertime(new Date());
            order.setTotal(cart.getTotal());
            order.setState(Constant.ORDER_WEIFUKUAN);
            order.setUser(user);

            for (CartItem item : cart.getCartItems()) {
                OrderItem orderItem = new OrderItem();
                orderItem.setItemid(UUIDUtils.getUUID());
                orderItem.setCount(item.getCount());
                orderItem.setSubtotal(item.getSubtotal());
                orderItem.setProduct(item.getProduct());
                orderItem.setOrder(order);

                order.getItems().add(orderItem);
            }

            // 调用orderservice完成保存操作
            OrderService orderService = new OrderServiceImpl();
            orderService.save(order);

            // 请求转发到order_info.jsp
            request.setAttribute("bean", order);
        } catch (Exception e) {

        }
        return "/jsp/order_info.jsp";
    }

    public String findMyOrdersByPage(HttpServletRequest request, HttpServletResponse response) {
        try {
            int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
            int pageSize = 3;
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                request.setAttribute("msg", "请先登录");
                return "/jsp/msg.jsp";
            }

            // 2. 调用service获取当前页所有数据
            OrderService orderService = new OrderServiceImpl();
            PageBean<Order> bean = orderService.findMyOrdersByPage(pageNumber, pageSize, user.getUid());
            request.setAttribute("pb", bean);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "获取我的订单失败");
            return "/jsp/msg.jsp";
        }
        return "/jsp/order_list.jsp";
    }

    public String pay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取收获信息 获取oid 获取银行

        //2.调用service获取订单 修改收获人信息  更新订单

        //3.拼接给第三方的url

        //4.重定向


        try {
            //接受参数
            String address=request.getParameter("address");
            String name=request.getParameter("name");
            String telephone=request.getParameter("telephone");
            String oid=request.getParameter("oid");


            //通过id获取order
            OrderService s=(OrderService) BeanFactory.getBean("OrderService");
            Order order = s.getById(oid);

            order.setAddress(address);
            order.setName(name);
            order.setTelephone(telephone);

            //更新order
            s.update(order);


            // 组织发送支付公司需要哪些数据
            String pd_FrpId = request.getParameter("pd_FrpId");
            String p0_Cmd = "Buy";
            String p1_MerId = ResourceBundle.getBundle("merchantInfo").getString("p1_MerId");
            String p2_Order = oid;
            String p3_Amt = "0.01";
            String p4_Cur = "CNY";
            String p5_Pid = "";
            String p6_Pcat = "";
            String p7_Pdesc = "";
            // 支付成功回调地址 ---- 第三方支付公司会访问、用户访问
            // 第三方支付可以访问网址
            String p8_Url = ResourceBundle.getBundle("merchantInfo").getString("responseURL");
            String p9_SAF = "";
            String pa_MP = "";
            String pr_NeedResponse = "1";
            // 加密hmac 需要密钥
            String keyValue = ResourceBundle.getBundle("merchantInfo").getString("keyValue");
            String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt,
                    p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP,
                    pd_FrpId, pr_NeedResponse, keyValue);


            //发送给第三方
            StringBuffer sb = new StringBuffer("https://www.yeepay.com/app-merchant-proxy/node?");
            sb.append("p0_Cmd=").append(p0_Cmd).append("&");
            sb.append("p1_MerId=").append(p1_MerId).append("&");
            sb.append("p2_Order=").append(p2_Order).append("&");
            sb.append("p3_Amt=").append(p3_Amt).append("&");
            sb.append("p4_Cur=").append(p4_Cur).append("&");
            sb.append("p5_Pid=").append(p5_Pid).append("&");
            sb.append("p6_Pcat=").append(p6_Pcat).append("&");
            sb.append("p7_Pdesc=").append(p7_Pdesc).append("&");
            sb.append("p8_Url=").append(p8_Url).append("&");
            sb.append("p9_SAF=").append(p9_SAF).append("&");
            sb.append("pa_MP=").append(pa_MP).append("&");
            sb.append("pd_FrpId=").append(pd_FrpId).append("&");
            sb.append("pr_NeedResponse=").append(pr_NeedResponse).append("&");
            sb.append("hmac=").append(hmac);

            response.sendRedirect(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "支付失败");
            return "/jsp/msg.jsp";
        }

        return null;
    }
}
